<template>
  <div>
    <div class="search">
      <el-input placeholder="请输入商品名称查询" style="width: 200px" v-model="name"></el-input>
      <el-button type="info" plain style="margin-left: 10px" @click="load(1)">查询</el-button>
      <el-button type="warning" plain style="margin-left: 10px" @click="reset">重置</el-button>
    </div>

<!--    <div class="operation">-->
<!--      <el-button type="primary" plain @click="handleAdd">新增</el-button>-->
<!--      <el-button type="danger" plain @click="delBatch">批量删除</el-button>-->
<!--    </div>-->


    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane label="全部" name="all"></el-tab-pane>
      <el-tab-pane label="待审核" name="awaitingApproval"></el-tab-pane>
      <el-tab-pane label="审核通过" name="approved"></el-tab-pane>
      <el-tab-pane label="审核不通过" name="disapproved"></el-tab-pane>
    </el-tabs>


    <div class="table">
      <el-table :data="tableData" strip @selection-change="handleSelectionChange">
        <el-table-column label="序号" width="70" align="center" sortable>
          <template #default="{ row, $index }">
            {{ $index + 1 }} <!-- 这里是序号从1开始 -->
          </template>
        </el-table-column>
        <el-table-column prop="userId" label="用户id"></el-table-column>

        <el-table-column prop="empNumber" label="审核员工工号"></el-table-column>
        <el-table-column prop="name" label="评论商品名称"></el-table-column>
        <el-table-column prop="content" label="评论内容"></el-table-column>
        <el-table-column prop="commentTime" label="评论时间"></el-table-column>
        <el-table-column label="评论图片">
          <template v-slot="scope">
            <div style="display: flex; align-items: center">
              <el-image style="width: 60px; height: 60px; border-radius: 80%"
                        :src="scope.row.picture || defaultImageUrl"
                        :preview-src-list="[scope.row.picture || defaultPreviewUrl]"></el-image>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="likes" label="点赞数量"></el-table-column>
        <el-table-column label="操作" align="center" width="180" v-if="activeTab === 'awaitingApproval'" fixed="right">
          <template v-slot="scope">
            <!-- 审核按钮，只在待审核状态显示 -->
            <el-button size="mini" type="success" plain @click="handleEdit(scope.row)" v-if="activeTab === 'awaitingApproval'">审核</el-button>

            <el-button size="mini" type="danger" plain @click="del(scope.row.id)" v-if=" scope.row.username != 'admin' ">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
            background
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[5, 10, 20]"
            :page-size="pageSize"
            layout="total, prev, pager, next"
            :total="total">
        </el-pagination>
      </div>
    </div>
    <template>
      <el-dialog title="评论详情" :visible.sync="fromVisible" width="40%" :close-on-click-modal="false" destroy-on-close>
        <el-form :model="form" label-width="100px" style="padding-right: 50px" ref="formRef">
          <el-form-item label="用户ID">
            <el-input v-model="form.userId" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="审核员工编号">
            <el-input v-model="form.employeeId" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="评论商品名称">
            <el-input v-model="form.productId" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="评论内容">
            <el-input type="textarea" v-model="form.content" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="评论时间">
            <el-input v-model="form.commentTime" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="评论图片">
            <div style="display: flex; align-items: center">
              <el-image style="width: 60px; height: 60px; border-radius: 80%"
                        :src="form.picture || defaultImageUrl"
                        :preview-src-list="[form.picture || defaultPreviewUrl]"></el-image>
            </div>
          </el-form-item>
          <el-form-item label="点赞数量">
            <el-input v-model="form.likes" :disabled="true"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="fromVisible = false">关闭</el-button>
          <el-button @click="passAudit(1)" v-if="activeTab === 'awaitingApproval'">通 过</el-button>
          <el-button @click="passAudit(2)" v-if="activeTab === 'awaitingApproval'">不通过</el-button>
        </div>
      </el-dialog>
    </template>





  </div>
</template>

<script>
export default {
  name: "Product",
  data() {
    return {
      //默认图片
      defaultImageUrl: 'https://img0.baidu.com/it/u=2991630058,871933297&fm=253&fmt=auto&app=138&f=JPEG?w=300&h=300',
      //默认预览
      defaultPreviewUrl: 'https://img0.baidu.com/it/u=2594677340,3536341249&fm=253&fmt=auto&app=138&f=JPG?w=240&h=240',
      tableData: [],  // 所有的数据
      pageNum: 1,   // 当前的页码
      pageSize: 10,  // 每页显示的个数
      currentState: null, // 添加一个变量来存储当前选中的状态
      activeTab: 'all',
      productsData: [], // 商品数据
      specificationsData: [], // 所有规格数据
      filteredSpecifications: [], // 过滤后的规格数据
      minDate: new Date(), // 当前日期
      isAuditMode: false, // 是否是审核模式
      isShelfMode: false, // 是否是上架模式
      total: 0,
      name: null,
      state:null,
      fromVisible: false,
      form: {},
      user: JSON.parse(localStorage.getItem('xm-user') || '{}'),
      ids: []
    }
  },
  created() {
    this.activeTab = 'all'; // 设置默认激活的标签页为 '全部'
    this.load(1); // 调用 load 方法加载全部数据
    this.loadProducts();//获取商品信息
    this.loadSpcifications();//获取商品规格信息

  },
  methods: {
    passAudit(status) {
      console.log(status)

      if (this.user.admin === undefined){
        this.form.employeeId =this.user.employee.id
      }else {
        this.form.employeeId =this.user.admin.id
      }


      // 设置状态
      this.form.status = status;
      //添加审核员工id
      // 调用保存方法，因为我们已经设置了状态，所以可以直接保存
      this.save();
    },
    disablePastDate(time) {
      const date = new Date();
      date.setDate(date.getDate() + 7); // 当前日期加7天
      return time < date;
    },

    loadProducts() { //获取商品数据
      if (this.user.admin === undefined){
        this.$request.get('/employee/api/product/pages').then(res => {
          this.productsData = res.records;
          console.log( this.productsData)
          this.productsData = this.uniqueProducts(this.productsData);
        }).catch(error => {
          console.error('获取商品数据失败:', error);
        });
      }else{
        this.$request.get('/admin/api/product/pages').then(res => {
          this.productsData = res.records;
          console.log( this.productsData)
          this.productsData = this.uniqueProducts(this.productsData);
        }).catch(error => {
          console.error('获取商品数据失败:', error);
        });
      }

    },
    uniqueProducts(products) { //去重方法
      const uniqueProducts = new Map();
      products.forEach((product) => {
        if (!uniqueProducts.has(product.id)) {
          uniqueProducts.set(product.id, product);
        }
      });
      return Array.from(uniqueProducts.values());
    },
    loadSpcifications() { //获取商品数据
      if (this.user.admin === undefined){
        this.$request.get('/employee/api/specifications/pages').then(res => {
          this.specificationsData = res.records;
          console.log(this.specificationsData)
        }).catch(error => {
          console.error('获取商品数据失败:', error);
        });
      }else {
        this.$request.get('/admin/api/specifications/pages').then(res => {
          this.specificationsData = res.records;
          console.log(this.specificationsData)
        }).catch(error => {
          console.error('获取商品数据失败:', error);
        });
      }

    },
    handleProductChange(productId) {
      this.filteredSpecifications = this.specificationsData.filter(spec => spec.productId === productId);
      // 遍历数组来找到匹配的规格并设置价格
      this.filteredSpecifications.forEach((spec) => {
        if (spec.id === this.form.specificationsId) {
          this.form.price = spec.price;
          return; // 找到匹配的规格后可以停止遍历
        }
      });
    },
    formatState(row, column, cellValue) {
      // 根据state的值返回相应的文本
      switch(cellValue) {
        case 0:
          return '待审核';
        case 1:
          return '已审核';
        default:
          return '未知状态';
      }
    },
    handleAdd() {   // 新增数据
      this.form = {
        state: '0', //状态默认为未上架
      }
      this.isAuditMode = false; // 设置为编辑模式
      this.fromVisible = true   // 打开弹窗
    },
    handleEdit(row) {   // 审核数据表单数据
      this.form = JSON.parse(JSON.stringify(row)); // 深拷贝数据
      // 确保触发商品规格变化的方法来更新价格
      this.handleProductChange(this.form.productId);
      this.isAuditMode = true; // 设置为审核模式
      this.fromVisible = true; // 打开弹窗
    },
    handleOffShelf(row) {   // 设置上架
      this.form = JSON.parse(JSON.stringify(row)); // 深拷贝数据
      // 确保触发商品规格变化的方法来更新价格
      this.handleProductChange(this.form.productId);
      this.isAuditMode = true; // 设置为审核模式
      this.isShelfMode = false; // 设置为上架模式
      this.fromVisible = true; // 打开弹窗
    },
    handleOnShelf(row) {   // 设置下架
      this.form = JSON.parse(JSON.stringify(row)); // 深拷贝数据
      // 确保触发商品规格变化的方法来更新价格
      this.handleProductChange(this.form.productId);
      this.isAuditMode = true; // 设置为审核模式
      this.isShelfMode = true; // 设置为上架模式
      this.fromVisible = true; // 打开弹窗
    },
    save() {   // 保存按钮触发的逻辑  它会触发新增或者更新
      this.$refs.formRef.validate((valid) => {
        if (this.user.admin === undefined){
          if (valid) {
            this.$request({
              url: this.form.id ? '/employee/api/comments/update' : '/employee/api/comments/add',
              method: this.form.id ? 'PUT' : 'POST',
              data: this.form
            }).then(res => {
              if (res.code === 0) {  // 表示成功保存
                this.$message.success('保存成功')
                this.load(1)
                this.fromVisible = false
              } else {
                this.$message.error(res.msg)  // 弹出错误的信息
                console.log(res)
              }
            })
          }
        }else {
          if (valid) {
            this.$request({
              url: this.form.id ? '/admin/api/comments/update' : '/admin/api/comments/add',
              method: this.form.id ? 'PUT' : 'POST',
              data: this.form
            }).then(res => {
              if (res.code === 0) {  // 表示成功保存
                this.$message.success('保存成功')
                this.load(1)
                this.fromVisible = false
              } else {
                this.$message.error(res.msg)  // 弹出错误的信息
                console.log(res)
              }
            })
          }
        }

      })
    },
    del(id) {   // 单个删除
      if (this.user.admin === undefined){

      }else {

      }
      this.$confirm('您确定删除吗？', '确认删除', {type: "warning"}).then(response => {
        this.$request.delete('/admin/api/comments/delete/' + id).then(res => {
          if (res.code === 0) {   // 表示操作成功
            this.$message.success('操作成功')
            this.load(1)
          } else {
            this.$message.error(res.msg)  // 弹出错误的信息
          }
        })
      }).catch(() => {
      })
    },
    handleSelectionChange(rows) {   // 当前选中的所有的行数据
      this.ids = rows.map(v => v.id)
    },

    handleTabClick(tab) {
      switch(tab.name) {
        case 'awaitingApproval':
          this.currentState = 0; // 待审核
          break;
        case 'approved':
          this.currentState = 1; // 未通过
          break;
        case 'disapproved':
          this.currentState = 2; // 待上架
          break;
        case 'all':
          this.currentState = null; // 全部
          break;
        default:
          this.currentState = null;
      }
      // 根据选中的标签页重新加载数据
      this.load(1);
    },
    load(pageNum) {
      if (pageNum) this.pageNum = pageNum;
      let requestUrl = this.user.admin === undefined ? '/employee/api/comments/pages' : '/admin/api/comments/pages';
      this.$request.get(requestUrl, {
        params: {
          current: this.pageNum,
          size: this.pageSize,
          // 添加状态参数，如果currentState为null，则不传递该参数，即查询所有状态
          status: this.currentState !== null ? this.currentState : undefined,
        }
      }).then(res => {
        this.tableData = res.records;
        this.total = res.total;
      })
    },


    handleCurrentChange(pageNum) {
      this.load(pageNum)
    },
    handleAvatarSuccess(response, file, fileList) {
      // 把头像属性换成上传的图片的链接
      this.form.imageUrl = response.data
    },
    reset() {
      this.name = null
      this.load(1)
    },
  }
}
</script>

<style scoped>

</style>